package com.xr.common;

/**
 * 位图实现
 * @author Arnold Yand
 * @time 2018/11/07 11:35
 */
public final class BitMap {
  private long length;

  /**
   * 1byte = 8bit
   * long 64 bit
   */
  private long[] bitArray = null;
  private static final int WORD_BITS = 64;

  public BitMap(int length){
    this.length = length;
    int bitArraysize = (length / WORD_BITS) + ((length % WORD_BITS) > 0 ? 1 : 0);
    bitArray = new long[bitArraysize];
  }

  /**
   * 将下标为idx的位置置为value
   *
   * @param idx 从0开始计数
   * @param value true:1 false:0
   */
  public void setBit(int idx, boolean value){
    if (value) {
      bitArray[wordIndex(idx)] ^= (1L << idx);
    } else {
      bitArray[wordIndex(idx)] &= ~(1L << idx);
    }
  }

  /**
   * 获取下标为idx的值
   * @param idx
   * @return
   */
  public boolean getBit(int idx){
    return (bitArray[wordIndex(idx)] & (1L << idx)) != 0;
  }

  /**
   * 找到包含下标idx的数组元素位置
   * @param idx
   * @return
   */
  private int wordIndex(int idx){
    return idx / WORD_BITS;
  }

  public long getLength() {
    return length;
  }
}
